package cn.wzy.utils;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

public class UploadingFile {

    private  final static String rootPath = "D:/corretto-1.8.0_282/permission_system/src/main/resources/static/img";

    public static String upload(MultipartFile fileUpload) {
        File fileDir = new File(rootPath);
//            不存在重新创建
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
//           判断参数是否为空
        if (fileUpload != null) {
            try {
                String prefix = UUID.randomUUID().toString().replaceAll("-", "");
                String fileName = prefix + "_" + fileUpload.getOriginalFilename();
                InputStream in = fileUpload.getInputStream();
                ;//声明输入输出流
                OutputStream out = new FileOutputStream(new File(rootPath + "\\" + fileName));//指定输出流的位置;
                //使用IOUtils.copy实现文件复制
                IOUtils.copy(in, out);
                in.close();
                out.close();
//                    上传成功
                return fileName;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    public static void download(String fileName, HttpServletResponse response) {
        File file = new File(rootPath, fileName);
        if (file.exists()) {
            try {
                FileInputStream in = new FileInputStream(file);
                //2.获取输出流
                //2.1.设置文件下载的名字  -- 附件表示做下载或上传操作，浏览器就不会将文件的内容直接显示出来了
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                //2.2.获取输出流
                ServletOutputStream out = response.getOutputStream();

                //3.实现下载
                IOUtils.copy(in, out);
                //关流，释放资源
                out.close();
                in.close();
            }catch (Exception e){
                throw new RuntimeException("文件下载错误");
            }
        }
    }
}
